<?php
header('Content-type: text/plain; charset=utf-8');
header("Pragma: no-cache");
header("Expires: 0");


require("includes/foxydb.php");

$foxydb = new Foxydb();

Class FoxySite{
 
  //
  //Site -1----------* Site2Category *----------1- Category
  //
  function getRelatedSitesByUriPrePath($pUriPrePath,$num=60,$pnum=10){
		global $foxydb;


		$foxydb->open();

		$site = $foxydb->findSiteByUri($pUriPrePath);

		$primaryPath = $foxydb->findCategoryPrimaryPath($site["primarycatsid"]);
		$result["primarypath"] = $primaryPath;

		$primaryAreaPath = $foxydb->findCategoryPrimaryPath($site["primaryareacatsid"]);
		$result["primaryareapath"] = $primaryAreaPath;
		
		$result["site"] = array($site);
		foreach ($primaryPath as $cat){

			if($cat["sid"] == $site["primarycatsid"]){
				$sites = $foxydb->selectSitesByCatSid($cat["sid"],$num);
			}else{
				$count = $foxydb->findSiteCountByCatSid($cat["sid"]);
				$start = rand(0, $count);
				$sites = $foxydb->selectSitesByCatSid($cat["sid"],$pnum,$start);
			}

			if($result["site"] ){
				if($sites){
					$result["site"] = array_merge($result["site"],$sites);
				}
			}else{
				$result["site"] = $sites;
			}
		}

		foreach ($result["site"] as $site){
			$s2cs = $foxydb->selectSite2CategoriesBySiteSid($site["sid"]);
			if($result["s2c"] ){
				if($s2cs){
					$result["s2c"] = array_merge($result["s2c"],$s2cs);
				}
			}else{
				$result["s2c"] = $s2cs;
			}
		}

		$foxydb->close();
	 
	   return $result;
  }
 
 };
 

 //access by http://localhost:8080/index.php?u=www.eetchina.com
 //echo "parameter u=".$_GET["u"]."<br><br>";
 $fs = new FoxySite();
 $result = $fs->getRelatedSitesByUriPrePath($_GET["uri"]);
 

 foreach ($result["site"] as $site){
	 $retSite = array($site["sid"],$site["uri"],$site["name"],$site["searchpath"]);
	 $ret["site"][] = $retSite; 
 }

 foreach ($result["s2c"] as $s2c){
	 $rets2c = array($s2c["sid"],$s2c["sitesid"],$s2c["catsid"],$s2c["seqno"]);
	 $ret["s2c"][] = $rets2c; 
 }

 //the primary path for the site identified by $_GET["u"]
 foreach ($result["primarypath"] as $cat){
	 //$retcat = array($cat["sid"],$cat["psid"],$cat["name"]);
	 $ret["path"][] = $cat["sid"]; 
 }

 foreach ($result["primaryareapath"] as $cat){
	 //$retcat = array($cat["sid"],$cat["psid"],$cat["name"]);
	 $ret["areaPath"][] = $cat["sid"]; 
 }

 $jsonObject = json_encode($ret);
 echo $jsonObject;
?>